package com.py.credit.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.entity.ApplicationEntity;
import com.py.credit.entity.AuthorizeRecord;
import com.py.credit.entity.BranchEntity;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.EasyCreditLogEntity;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.entity.HireEntity;
import com.py.credit.entity.HirePersonEntity;
import com.py.credit.entity.ReportCustom;
import com.py.credit.entity.SysUser;

import com.py.credit.entity.enums.EasyCreditApplicationEnum;
import com.py.credit.service.AuthorizeModelService;
import com.py.credit.service.AuthorizeRecordService;
import com.py.credit.service.EasyCreditApplicationService;
import com.py.credit.service.GatewayAuthenticationService;
import com.py.credit.service.GatewayUserService;
import com.py.credit.service.SysDictService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.CompressUtil;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.HtmlToPdfUtils;
import com.py.credit.utils.IdCardCheckUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.controller.BaseController;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/easyCredit")
public class EasyCreditApplicationController extends BaseController {

	private static String FRONT_TABLE_ID = "easyCredit";

	private static String APPLICATION_TYPE_TOUR = "信易游";

	private static String APPLICATION_TYPE_HIRE = "信易签";

	@Autowired
	private EasyCreditApplicationService easyCreditApplicationService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	private GatewayAuthenticationService gatewayAuthenticationService;

	@Autowired
	private SysDictService sysDictService;

	@Autowired
	private GatewayUserService gatewayUserService;

	@Autowired
	private AuthorizeRecordService authorizeRecordService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${qrcode.url}")
	private String url;

	@Value("${pdfJsPath}")
	private String pdfJsPath;

	@Value("${googlePath}")
	private String googlePath;

	@Value("${ht.url}")
	private String htUrl;
	@Value("${sqs.url}")
	private String sqsUrl;
	/**
	 * \ 应用列表
	 * 
	 * @param name      应用名
	 * @param userType  面向人群
	 * @param condition
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getTableList.json", method = RequestMethod.GET)
	public RestServiceResult<List<ApplicationEntity>> getTableList(
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "userType", required = false) String userType,
			@RequestParam(value = "condition", required = false) String condition, Page page,
			HttpServletRequest request) {

		RestServiceResult<List<ApplicationEntity>> result = new RestServiceResult<>();

		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? EasyCreditApplicationEnum.getDefaultShowColumnEN()
				: Arrays.asList(configColumns);
		List<ApplicationEntity> data = easyCreditApplicationService.selectByConditionForPage(name, userType,
				showColumns, new String[] { "id", "valid_time" }, condition, page);
		result.setCount(page.getTotalCount());
		result.setData(data);
		return result;
	}

	/**
	 * 添加应用信息
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/add.json")
	public RestServiceResult<Object> add(@RequestBody ApplicationEntity entity) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			easyCreditApplicationService.add(entity);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("添加应用信息失败");
		}
		return result;
	}

	/**
	 * 修改应用信息
	 * 
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/modify.json")
	public RestServiceResult<Object> modify(@RequestBody ApplicationEntity entity) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			easyCreditApplicationService.modify(entity);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("更新应用信息失败");
		}
		return result;
	}

	/**
	 * 查询单个模型信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOneModel.json")
	public RestServiceResult<Object> getOneModel() {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.getOneModel());
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询单个模型失败");
		}
		return result;
	}

	/**
	 * 查询单个应用信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getOneInfo.json", method = RequestMethod.GET)
	public RestServiceResult<Object> getOneInfo(@RequestParam(value = "id", required = true) String id) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.getOneInfo(id, null));
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询单个应用失败");
		}
		return result;
	}

	/**
	 * 查询申请信息列表
	 * 
	 * @param ztmc
	 * @param applicationType
	 * @param batchId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/getBranchInfo.json", method = RequestMethod.GET)
	public RestServiceResult<Object> getBranchInfo(@RequestParam(value = "ztmc", required = false) String ztmc,
			@RequestParam(value = "applicationType", required = true) String applicationType,
			@RequestParam(value = "batchId", required = true) String batchId, Page page) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.getBranchInfo(ztmc, applicationType, batchId, page));
			result.setCount(page.getTotalCount());
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询单个应用信息失败");
		}
		return result;
	}

	/**
	 * 添加批次表信息
	 * 
	 * @param beginTime
	 * @param endTime
	 * @param batchType
	 * @param productNum
	 * @return
	 */
	@RequestMapping(value = "/addBatch.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addBatch(
			@RequestParam(value = "beginTime", defaultValue = "", required = false) String beginTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
			@RequestParam(value = "batchType", defaultValue = "", required = true) String batchType,
			@RequestParam(value = "productNum", defaultValue = "", required = true) String productNum) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {

			if (("2").equals(easyCreditApplicationService.checkInUseApp(APPLICATION_TYPE_TOUR))) {
				result.setMsg("发布失败，信易游未启用！");
				return result;
			}
			if (("1").equals(batchType) && (null != easyCreditApplicationService.selectOneBatch())) {
				result.setMsg("已有批次启用，请关闭后重试！");
				return result;
			}
			easyCreditApplicationService.addBatch(beginTime, endTime, batchType, productNum);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("添加信易游批次表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("添加信易游批次表失败！");
		}
		return result;
	}

	/**
	 * 删除批次表信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteBatch.json", method = RequestMethod.POST)
	public RestServiceResult<Object> deleteBatch(@RequestParam(value = "ids", required = true) List<String> ids) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			easyCreditApplicationService.deleteBatch(ids);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("删除信易游批次表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("删除信易游批次表失败！");
		}
		return result;
	}

	/**
	 * 查询单个批次信息
	 * 
	 * @param batch_id
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/selectBatch.json", method = RequestMethod.GET)
	public RestServiceResult<Object> selectBatch(@RequestParam(value = "batch_id", required = false) String batch_id,
			Page page) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.selectBatch(batch_id, page));
			result.setCount(page.getTotalCount());
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("查询信易游批次表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询信易游批次表失败！");
		}
		return result;
	}

	/**
	 * 添加信易游信息
	 * 
	 * @param applicationType
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addTour.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addBranch(
			@RequestParam(value = "applicationType", required = true) String applicationType,
			HttpServletRequest request) {
		String dirPath = absolutepath + File.separator + "easyCredit" + File.separator
				+ UuidUtil.getInstance().getUUid();
		RestServiceResult<Object> result = new RestServiceResult<>();
		BranchEntity entity = new BranchEntity();
		entity.setApplicationType(applicationType);
		GatewayUserEntity user;
		try {
			// 通过字典查询应用的信息
			List<DictDetailEntity> dictApp = sysDictService.getDictDetails("YYLX", entity.getApplicationType());
			ApplicationEntity applicationEntity = easyCreditApplicationService
					.getOneInfo(null, dictApp.get(0).getDtlValue()).get(0);
			user = gatewayAuthenticationService.getCurrentUserInfo(HttpServletHelper.getUserXypjGatewayToken(request));
			if (null != user) {
				String userId = String.valueOf(user.getId());
				entity.setUserId(userId);
				entity.setIsPass(user.getUsername());
				;
			} else {
				result.setMsg("系统繁忙，请稍后重试！");
				return result;
			}
			easyCreditApplicationService.addBranch(entity, applicationEntity, dirPath, url);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("添加分支表成功！");
		} catch (Exception e1) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("添加分支表失败！");
		}
		return result;
	}

	/**
	 * 校验信易游权利接口
	 * 
	 * @param id
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/updateBranchInUse.json", method = RequestMethod.GET)
	public String updateBranchInUse(@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "token", required = true) String token) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			AuthorizeRecord record = authorizeRecordService.selectRecord(token);
			if (record == null) {
				result.setMsg("无效token！");
				return result.getMsg();
			}
			if (("1").equals(easyCreditApplicationService.checkInUse(record.getBranchId()))) {
				result.setMsg("该二维码已被使用！");
			} else {
				easyCreditApplicationService.updateBranchInUse(id);
				authorizeRecordService.deleteRecordByToken(token);
				result.setCode(RestServiceResult.CODE_SUCCESS);
				result.setMsg("用户使用二维码成功！");
			}
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统繁忙，请稍后再试！");
		}
		return result.getMsg();
	}

	/**
	 * 添加信易租信息
	 * 
	 * @param entity
	 * @param hPP      房产证照片
	 * @param request
	 * @return 
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = "/addHire.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addHire(HireEntity entity,
			@RequestParam(value = "personStr", required = false) String personStr,
			@RequestParam(value = "num", required = true) int num,
			@RequestParam(value = "hpp", required = true) MultipartFile hPP, HttpServletRequest request)
			throws IllegalStateException, IOException {
		String userId = "";
		GatewayUserEntity user;
		RestServiceResult<Object> result = new RestServiceResult<>();
		BranchEntity branchEntity = new BranchEntity();
		branchEntity.setApplicationType("2");
		try {
			// 通过字典获取应用信息
			List<DictDetailEntity> dictApp = sysDictService.getDictDetails("YYLX", "2");
			ApplicationEntity applicationEntity = easyCreditApplicationService
					.getOneInfo(null, dictApp.get(0).getDtlValue()).get(0);
			user = gatewayAuthenticationService.getCurrentUserInfo(HttpServletHelper.getUserXypjGatewayToken(request));
			if (null != user) {
				userId = String.valueOf(user.getId());
				branchEntity.setUserId(userId);
				branchEntity.setIsPass(user.getUsername());
			} else {
				result.setMsg("系统繁忙，请稍后重试！");
				return result;
			}
			boolean f = easyCreditApplicationService.getHireByProve(entity.getBelongProveNumber(),entity.getHireStartTime(),entity.getHireEndTime());
			if(!f) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("您的房产证号已被锁定，请重试");
				return result;
			}
			String dirPath = absolutepath + File.separator + "easyCredit" + File.separator + user.getSjhm();
			List<HirePersonEntity> personList = JSONObject.parseArray(personStr, HirePersonEntity.class);
			MultipartFile[] photoList = getPicture(request,num);
			for(int i = 0;i<personList.size();i++) {
				MultipartFile cf = photoList[2*i];
				MultipartFile cb = photoList[2*i+1];
				if(null != cf) {
					gatewayUserService.fileUpload(cf, dirPath, "xyzl_");
					personList.get(i).setCardFront(dirPath + "/xyzl_" + cf.getOriginalFilename());
				}
				if(null != cb) {
					gatewayUserService.fileUpload(cb, dirPath, "xyzl_");
					personList.get(i).setCardBack(dirPath + "/xyzl_" + cb.getOriginalFilename());
				}
				String id = UuidUtil.getUUid();
				personList.get(i).setId(id);
			}
			if (null != hPP) {
				gatewayUserService.fileUpload(hPP, dirPath, "xyzl_");
				entity.setHouseProvePic(dirPath + "/xyzl_" + hPP.getOriginalFilename());
			}
			entity.setPerson(personList);
			String id = UuidUtil.getUUid();
			entity.setId(id);
			easyCreditApplicationService.addQRCode(entity,dirPath);
			// 压缩上传的资质证件
			StringBuilder sb = new StringBuilder();
			sb.append(absolutepath + File.separator + "easyCredit" + File.separator + user.getSjhm() + ".zip")
					.append(",").append(user.getSjhm());
			CompressUtil.zip(dirPath);
			branchEntity.setPath(sb.toString());
			entity.setApplyType("1");
			easyCreditApplicationService.addHire(entity, userId);
			branchEntity.setId(UuidUtil.getUUid());
			branchEntity.setInfoId(id);
			easyCreditApplicationService.addBranch(branchEntity, applicationEntity, null, null);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("添加租赁表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("添加租赁表失败！");
		}
		return result;
	}

	/**
	 * 添加日志信息
	 * 
	 * @param entity
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addLog.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addLog(@RequestBody EasyCreditLogEntity entity, HttpServletRequest request) {
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		String userId = "";
		String dirPath = absolutepath + File.separator + "easyCredit" + File.separator
				+ UuidUtil.getInstance().getUUid();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {
				userId = String.valueOf(userInfo.getId());
				entity.setShr(userId);
			} else {

				ExceptionLogger.error("EasyCreditApplicationController#addLog", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("EasyCreditApplicationController#addLog", "未获取到当前用户信息！");
		}
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			int num = easyCreditApplicationService.getHireCountByRecordNo(entity.getRecordNo());
			if (num > 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("该备案号已存在，请重试");
				return result;
			}
			easyCreditApplicationService.addLog(entity, url, dirPath);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("添加日志表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("添加日志表失败！");
		}
		return result;
	}

	/**
	 * 查询单条租赁信息
	 * 
	 * @param infoId
	 * @return
	 */
	@RequestMapping(value = "/selectHire.json", method = RequestMethod.GET)
	public RestServiceResult<HireEntity> selectHire(@RequestParam(value = "infoId", required = false) String infoId) {

		RestServiceResult<HireEntity> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.selectHire(infoId));
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("查询租赁表成功！");
			;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询租赁表失败！");
		}
		return result;
	}

	/**
	 * 查询多条租赁信息
	 * 
	 * @param infoId
	 * @return
	 */
	@RequestMapping(value = "/getHire.json", method = RequestMethod.GET)
	public RestServiceResult<List<HireEntity>> getHireForWeixin(HttpServletRequest request) {
		RestServiceResult<List<HireEntity>> result = new RestServiceResult<>();
		String userId = "";
		GatewayUserEntity user;
		try {
			user = gatewayAuthenticationService.getCurrentUserInfo(HttpServletHelper.getUserXypjGatewayToken(request));
			userId = user.getId() + "";
		} catch (Exception e1) {
			result.setMsg("系统繁忙，请稍后重试！");
			return result;
		}
		try {
			result.setData(easyCreditApplicationService.getHireForWeixin(userId));
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("查询租赁表成功！");
			;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询租赁表失败！");
		}
		return result;
	}

	/**
	 * 查询日志信息
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/selectLog.json", method = RequestMethod.GET)
	public RestServiceResult<Object> selectLog(HttpServletRequest request, Page page) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			List<EasyCreditLogEntity> log = easyCreditApplicationService.selectLog(page);
			if (!CollectionUtils.isEmpty(log)) {
				Set<Integer> userIds = new HashSet<Integer>();
				for (EasyCreditLogEntity map : log) {
					if (null != map && null != map.getShr()) {
						userIds.add(Integer.parseInt(map.getShr()));
					}
				}
				List<EasyCreditLogEntity> matchUserNameEntity = xypjRemoteBaseService.matchUserNameEntity(log,
						HttpServletHelper.getUserToken(request), userIds);
				result.setData(matchUserNameEntity);
				result.setCount(page.getTotalCount());
			}
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("查询日志表成功！");
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询日志表失败！");
		}
		return result;
	}

	/**
	 * 校验应用是否使用
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/checkInUseApp.json", method = RequestMethod.GET)
	public RestServiceResult<Object> checkInUseApp(@RequestParam(value = "id", required = true) String id) {

		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.checkInUseApp(id));
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("校验app是否使用成功！");
			;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("校验app是否使用失败！");
		}
		return result;
	}

	/**
	 * 获取token详情列表
	 * 
	 * @param batchId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/getTokenDetail.json", method = RequestMethod.GET)
	public RestServiceResult<List<Map<String, Object>>> getTokenDetail(
			@RequestParam(value = "batchId", required = true) String batchId, Page page) {
		List<Map<String, Object>> detail = easyCreditApplicationService.getTokenDetail(batchId, page);
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), detail);
	}

	/**
	 * 停用丶启用批次信息
	 * 
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/updateBatchIsUser.json", method = RequestMethod.POST)
	public RestServiceResult<Map> updateBatchIsUser(@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "type", required = true) String type) {
		RestServiceResult<Map> result = new RestServiceResult<>();
		if (!"2".equals(type) && null != easyCreditApplicationService.selectOneBatch()) {
			result.setMsg("有正在启用的批次，请关闭后重试");
			return result;
		}
		easyCreditApplicationService.updateBatchIsUser(id, type);
		result.setCode(RestServiceResult.CODE_SUCCESS);
		result.setMsg("修改启用状态成功！");
		return result;
	}

	@RequestMapping(value = "/reportExport.do")
	public RestServiceResult<List<Map<String, Object>>> reportExport(
			@RequestParam(value = "infoId", required = true) String infoId, HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<>();
		try {
			HireEntity hire = this.selectHire(infoId).getData();
			String mc = hire.getLocation();
			String url = htUrl + "?id=" + infoId;
			boolean googleConvent = HtmlToPdfUtils.googleConvent(pdfJsPath, url,
					absolutepath + ResourcePath.CREDIT_REPORT_DIR + infoId, mc + ".pdf", null, false, googlePath);
			if (googleConvent) {
				r.setData(rep);
				return r;
			} else {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("生成报告失败");
				ExceptionLogger.error("ReportContentController#reportExport", "生成报告失败");
			}
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg(e.getMessage());
			ExceptionLogger.error("ReportContentController#reportExport", "前台报告历史查询失败");
		}
		r.setData(rep);
		return r;
	}

	@RequestMapping(value = "/download.json")
	@ResponseBody
	public void download(@RequestParam(value = "infoId", required = true) String infoId, HttpServletRequest request,
			HttpServletResponse response) {
		String path = "C:\\sgs\\reports\\";

		HireEntity hire = this.selectHire(infoId).getData();
		String mc = hire.getLocation();
		path += infoId + "\\" + mc + ".pdf";
		FileUtil.uploadFile(path, request, response);
	}

	@RequestMapping(value = "/getHistory.json")
	@ResponseBody
	public RestServiceResult<List<Map<String, Object>>> getHistory(Page page,
			@RequestParam(value = "id", defaultValue = "", required = false) String id, HttpServletRequest request,
			HttpServletResponse response) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		try {
			result.setData(easyCreditApplicationService.getHistoryByPage(page, id));
			result.setCount(page.getTotalCount());
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);

			result.setMsg("查询信息失败");
		}
		return result;
	}

	@RequestMapping("/addReportElement.json")
	public RestServiceResult<List<Map<String, Object>>> addReportConfig(
			@RequestParam(value = "reportWatermark", required = false) CommonsMultipartFile reportWatermark)
			throws IOException {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		String backGround = absolutepath + "/" + FRONT_TABLE_ID + ResourcePath.WATERMAERK_IMAGES_DIR;
		easyCreditApplicationService.addReportConfig(backGround, reportWatermark);
		return result;
	}

	@RequestMapping("/getReportDetail.json")
	public void getReportTextElement(HttpServletResponse response) throws IOException {
		Map<String, Object> latest = easyCreditApplicationService.getLatest();
		String path = (String) latest.get("path");
		openFile(path, response);
	}

	@RequestMapping("/getContractBarcode.json")
	public void getContractBarcode(@RequestParam(value = "id", defaultValue = "", required = false) String infoId,
			HttpServletResponse response) throws IOException {
		HireEntity hire = easyCreditApplicationService.selectHire(infoId);
		String path = hire.getRecordNoPath();
		openFile(path, response);
	}
	
	@RequestMapping(value = "/applicationBookExport.do")
	public RestServiceResult<List<Map<String, Object>>> applicationBookExport(
			@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "location", required = true) String location, HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
		List<Map<String, Object>> rep = new ArrayList<>();
		try {
			String url = sqsUrl + "?id=" + id;
			boolean googleConvent = HtmlToPdfUtils.googleConvent(pdfJsPath, url,
					absolutepath + ResourcePath.CREDIT_REPORT_DIR+"申请书/"+ id, location + ".pdf", null, false, googlePath);
			if (googleConvent) {
				r.setData(rep);
				return r;
			} else {
				r.setCode(RestServiceResult.CODE_UNKNOW);
				r.setMsg("生成报告失败");
				ExceptionLogger.error("ReportContentController#reportExport", "生成报告失败");
			}
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg(e.getMessage());
			ExceptionLogger.error("ReportContentController#reportExport", "前台报告历史查询失败");
		}
		r.setData(rep);
		return r;
	}
	
	
	@RequestMapping("/getApplicationBook.json")
	private void getApplicationBook(@RequestParam(value = "id", required = true)String id,
			@RequestParam(value = "location", required = true)String location,
			HttpServletResponse response) throws IOException {
		InputStream in = null;
		ServletOutputStream out = null;
		String filePath = "C:\\sgs" + ResourcePath.CREDIT_REPORT_DIR +"申请书/"+ id+"/"+location + ".pdf";
		try {
			response.reset();
			out = response.getOutputStream();
			response.setContentType("application/pdf");
			in = new BufferedInputStream(new FileInputStream(filePath));
			int ch;

			while ((ch = in.read()) != -1) {
				out.print((char) ch);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

	private void openFile(String path, HttpServletResponse response) throws IOException {
		if (null != path && !"".equals(path)) {
			response.setContentType("image/png");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputSream = response.getOutputStream();

			InputStream fileInputStream = new FileInputStream(path);
			byte[] data = this.toByteArray(fileInputStream);
			fileInputStream.close();

			InputStream in = new ByteArrayInputStream(data);
			in.close();
			int len = 0;

			byte[] buf = new byte[1024];
			while ((len = in.read(buf, 0, 1024)) != -1) {
				outputSream.write(buf, 0, len);
			}

			outputSream.close();
		}
	}

	private byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
	
	private MultipartFile[] getPicture(HttpServletRequest request,int num) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
		MultipartFile[] fileList = new MultipartFile[num*2];
	    if(multipartResolver.isMultipart(request)){  
	        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
	        Iterator<String> iter = multiRequest.getFileNames();  
	        int i = 0;
	        while(iter.hasNext()){  
	            MultipartFile file = multiRequest.getFile(iter.next());  
	            if(!"hpp".equals(file.getName())) {
	            	fileList[i] = file;
	            	i++;
	            }
	        }  
	    } 
	    return fileList;
	}
	
	/**
	 * 查询单条租赁信息
	 * 
	 * @param infoId
	 * @return
	 */
	@RequestMapping(value = "/selectHireCode.json", method = RequestMethod.GET)
	public RestServiceResult<HireEntity> selectHireCode(@RequestParam(value = "table", required = false) String table,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "infoId", required = false) String infoId,HttpServletResponse response) {

		RestServiceResult<HireEntity> result = new RestServiceResult<>();
		try {
			String path = easyCreditApplicationService.selectHireCode(table,type,infoId);
			openFile(path, response);
			result.setCode(RestServiceResult.CODE_SUCCESS);
			result.setMsg("查询二维码成功！");
			;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("查询二维码失败！");
		}
		return result;
	}
	/**
	 * 
	 * @Title: downXycnTemplate
	 * @Description: TODO(下载案例模板)
	 * @param request
	 * @param  httpResponse
	 * @param @throws IOException    设定文件
	 * @return void    返回类型
	 * @throws
	 */
	@RequestMapping(value = "/downTemplate.json")
	public void downXycnTemplate( HttpServletRequest request, HttpServletResponse httpResponse)
			throws IOException {
		FileUtils.downloadFile(this.getClass().getResource("/案例模板.xlsx").getPath(), httpResponse);

	}
	/**
	 * 
	 * @Title: importXyjCases
	 * @Description: TODO(导入案例数据)
	 * @param  request
	 * @param  httpResponse
	 * @param  file
	 * @param @return
	 * @param @throws IOException    设定文件
	 * @return RestServiceResult<Object>    返回类型
	 * @throws
	 */
	@RequestMapping(value = "/importXyjCases.json")
	public RestServiceResult<Object>  importXyjCases( HttpServletRequest request, HttpServletResponse httpResponse,@RequestParam(value = "file") CommonsMultipartFile file)
			throws IOException {
		RestServiceResult<Object> result = new RestServiceResult<>();

		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("EasyCreditApplicationController#importXyjCases", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 获取文件的后缀
				String fileType = null;
				if (file != null) {
					// 获取文件后缀
					if (file.getOriginalFilename().contains(".")) {
						fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
								file.getOriginalFilename().length());
					}
				} else {
					throw new ServiceException("上传的文件不得为空");// 抛出异常
				}
				if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType)) {
					throw new ServiceException("上传的文件格式不支持。");
				}
				
				// 读取excel所有记录数
				List<List<String>> lists = readExcel(file);
				//删除标题行
				lists.remove(0);
				try {
					for(List list : lists) {
						String batchId = UuidUtil.getUUid();
						easyCreditApplicationService.addCases(batchId,list.get(0).toString(),list.get(1).toString(),
								list.get(2).toString(),list.get(3).toString(),list.get(4).toString(),
								list.get(5).toString(),list.get(6).toString(),list.get(7).toString(),userInfo.getOfficeId(),userInfo.getId());
					}
				} catch (Exception e) {
					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("系统异常，请稍后再试！");
					ExceptionLogger.error("EasyCreditApplicationController#importXyjCases", "数据导入失败！");
					return result;
				}
				
				
		return result;

	}

    /**
     * 查询案例信息
     *
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "/selectCase.json")
    public RestServiceResult<Object> selectCase(HttpServletRequest request, Page page, String type,String xyjcp) {

        RestServiceResult<Object> result = new RestServiceResult<>();
        try {
            List<Map<String,String>> log = easyCreditApplicationService.selectCaseForPage(page, type,xyjcp);
            if (!CollectionUtils.isEmpty(log)) {
                result.setData(log);
                result.setCount(page.getTotalCount());
            }
            result.setCode(RestServiceResult.CODE_SUCCESS);
            result.setMsg("查询案例成功！");
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);

            result.setMsg("查询案例失败！");
        }
        return result;
    }
    /**
     * 
     * @Title: selectCaseDetail
     * @Description: TODO(查看详情)
     * @param @param request
     * @param @param batchId
     * @param @return    设定文件
     * @return RestServiceResult<Object>    返回类型
     * @throws
     */
    @RequestMapping(value = "/selectCaseDetail.json")
    public RestServiceResult<Object> selectCaseDetail(HttpServletRequest request, String batchId) {

        RestServiceResult<Object> result = new RestServiceResult<>();
        try {
            List<Map<String,String>> data = easyCreditApplicationService.selectCaseDetail(batchId);
          
                result.setData(data);            
 
            result.setCode(RestServiceResult.CODE_SUCCESS);
            result.setMsg("查询详情成功！");
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);

            result.setMsg("查询详情失败！");
        }
        return result;
    }
    @RequestMapping(value = "/deleteData.json")
	@ResponseBody
	public RestServiceResult<Object> deleteData(
			@RequestParam(value = "dataIds", defaultValue = "", required = true) String dataIds) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		String[] record_ids = dataIds.split(",");
		try {
			for (String id : record_ids) {
				easyCreditApplicationService.deleteData(id);
		}
			
		} catch (ServiceException e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(e.getMessage());
			ExceptionLogger.error("EasyCreditApplicationController#deleteData", "ERROR:" + e.getMessage(), e);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("案例数据删除异常，请稍后再试！");
			ExceptionLogger.error("EasyCreditApplicationController#deleteData", "ERROR:" + e.getMessage(), e);
			return result;
		}
		return result;
	}
    
    @RequestMapping(value = "/updateData.json")
  	@ResponseBody
  	public RestServiceResult<Object> updateData(
  			@RequestParam(value = "batch_id", defaultValue = "", required = true) String batch_id,
  			@RequestParam(value = "xyjcp", defaultValue = "", required = true) String xyjcp,
  			@RequestParam(value = "syztmc", defaultValue = "", required = true) String syztmc,
  			@RequestParam(value = "xydm", defaultValue = "", required = true) String xydm,
  			@RequestParam(value = "ztlx", defaultValue = "", required = true) String ztlx,
  			@RequestParam(value = "tgdw", defaultValue = "", required = true) String tgdw,
  			@RequestParam(value = "fksj", defaultValue = "", required = true) String fksj) {
  		RestServiceResult<Object> result = new RestServiceResult<>();
  		
  		try {
  			
  				easyCreditApplicationService.updateData(batch_id,xyjcp,syztmc,xydm,ztlx,tgdw,fksj);
  	
  			
  		} catch (ServiceException e) {
  			result.setCode(RestServiceResult.CODE_UNKNOW);
  			result.setMsg(e.getMessage());
  			ExceptionLogger.error("EasyCreditApplicationController#updateData", "ERROR:" + e.getMessage(), e);
  			return result;
  		} catch (Exception e) {
  			result.setCode(RestServiceResult.CODE_UNKNOW);
  			result.setMsg("案例数据编辑异常，请稍后再试！");
  			ExceptionLogger.error("EasyCreditApplicationController#delupdateDataeteData", "ERROR:" + e.getMessage(), e);
  			return result;
  		}
  		return result;
  	}
    
    @RequestMapping(value = "/deleteProduct.json")
   	@ResponseBody
   	public RestServiceResult<Object> deleteProduct(
   			@RequestParam(value = "ids", defaultValue = "", required = true) String ids) {
   		RestServiceResult<Object> result = new RestServiceResult<>();
   		String[] record_ids = ids.split(",");
   		try {
   			for (String id : record_ids) {
   				easyCreditApplicationService.deleteProduct(id);
   		}
   			
   		} catch (ServiceException e) {
   			result.setCode(RestServiceResult.CODE_UNKNOW);
   			result.setMsg(e.getMessage());
   			ExceptionLogger.error("EasyCreditApplicationController#deleteProduct", "ERROR:" + e.getMessage(), e);
   			return result;
   		} catch (Exception e) {
   			result.setCode(RestServiceResult.CODE_UNKNOW);
   			result.setMsg("产品数据删除异常，请稍后再试！");
   			ExceptionLogger.error("EasyCreditApplicationController#deleteProduct", "ERROR:" + e.getMessage(), e);
   			return result;
   		}
   		return result;
   	}

	/**
	 * 根据fileType不同读取excel文件
	 *
	 * @param path
	 * @param path
	 * @throws IOException
	 */
	@SuppressWarnings({ "resource", "deprecation" })
	public static List<List<String>> readExcel(MultipartFile file) {
		// String fileType = path.substring(path.lastIndexOf(".") + 1);
		// return a list contains many list

		// 获得文件名
		String fileName = file.getOriginalFilename();
		// 获取文件的后缀名 .xls/xlsx
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		List<List<String>> lists = new ArrayList<List<String>>();
		// 读取excel文件
		Workbook wb = null;
		try {
			if (suffix.equals("xls")) {
				wb = new HSSFWorkbook(file.getInputStream());
			} else {
				wb = new XSSFWorkbook(file.getInputStream());
			}
			// 读取第一个工作页sheet
			Sheet sheet = wb.getSheetAt(0);
			// 第一行为标题
			for (Row row : sheet) {
				ArrayList<String> list = new ArrayList<String>();
				if(!isRowEmpty(row)) {
					for (Cell cell : row) {
						// 根据不同类型"转化成字符串
						cell.setCellType(Cell.CELL_TYPE_STRING);
						list.add(cell.getStringCellValue());
					}
					lists.add(list);
				}
			
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (file.getInputStream() != null)
					file.getInputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return lists;
	}
	public static boolean isRowEmpty(Row row) {
		for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {	
		Cell cell = row.getCell(c);
		if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
		return false;
		}
		return true;
		}
	
}
